import React from 'react'
import { connect } from 'react-redux'
import { Form, Select, message, Switch, Button, Input, InputNumber, Radio, Row, Col } from 'antd';
import { messages } from "share/common";
import interfaceService from 'containers/financial-account/interface-definition/interface-service';
import constants from 'share/constants';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};

class ruleDefinedRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      record: {},
      saveLoading: false,
      interfaceRecord: {},
      type: ''
    }
  }

  componentWillMount() {

  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      record: nextProps.editRecord,
      interfaceRecord: nextProps.interfaceRecord
    }, () => {
      this.setState({ type: this.state.record.ruleDetail ? JSON.parse(this.state.record.ruleDetail).type : '' })
    });
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { record, interfaceRecord } = this.state;
        const { user, tenant } = this.props;
        record.id && (values.id = record.id);
        values.tenantId = tenant.id;
        values.setOfBooksId = interfaceRecord.setOfBooksId;
        values.functionId = interfaceRecord.id;
        let tempType = values.type;
        values.type = values.ruleCode === 'ExportCounter' ? 1001 : 1002;
        values.ruleDetail = {};
        typeof values.initialValue === 'number' && (values.ruleDetail.initialValue = values.initialValue);
        delete values.initialValue;
        values.stepLength && (values.ruleDetail.stepLength = values.stepLength);
        delete values.stepLength;
        tempType && (values.ruleDetail.type = tempType);
        values.length && (values.ruleDetail.length = values.length);
        delete values.length;
        values.ruleDetail = JSON.stringify(values.ruleDetail);
        let name = Object.keys(record).length > 0 ? 'updateRule' : 'addRule';
        this.setState({ saveLoading: true });
        interfaceService[name](values, user.userOID).then(() => {
          this.setState({ saveLoading: false });
          this.props.close(true);
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({ saveLoading: false });
        })
      }
    })
  };

  changeName = value => {
    constants.ruleDefined.map(item => {
      if (item.title === value) {
        this.props.form.setFieldsValue({ ruleCode: item.code, description: item.description });
      }
    })
  };

  changeRadio = e => {
    this.setState({ type: e.target.value });
  };

  render() {
    const { record, saveLoading, type } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Form style={{ marginTop: '10px' }}>
          <FormItem label={messages('financial-account.key25')/*规则名称*/} {...formItemLayout}>
            {getFieldDecorator('ruleName', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
              initialValue: record.ruleName
            })(
              <Select
                placeholder={messages('common.select')/*请选择*/}
                onChange={this.changeName}
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {
                  constants.ruleDefined.map(item => {
                    return <Option key={item.title}>{item.title}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key53')/*核算业务类型名称*/} {...formItemLayout}>
            {getFieldDecorator('ruleCode', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.ruleCode
            })(
              <Input placeholder={messages('common.please.enter')/*请输入*/} disabled/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key176')/*规则说明*/} {...formItemLayout}>
            {getFieldDecorator('description', {
              initialValue: record.description
            })(
              <TextArea rows={4} placeholder={messages('common.please.input')/*请输入*/} style={{ resize: 'none' }}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key177')/*起始值*/} {...formItemLayout}>
            {getFieldDecorator('initialValue', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.ruleDetail && JSON.parse(record.ruleDetail).initialValue
            })(
              <InputNumber step={1} min={0} precision={0} placeholder={messages('common.please.enter')/*请输入*/} style={{ width: '120px' }}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key179')/*步长*/} {...formItemLayout}>
            {getFieldDecorator('stepLength', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.ruleDetail && JSON.parse(record.ruleDetail).stepLength
            })(
              <InputNumber step={1} min={1} precision={0} placeholder={messages('financial-account.key178')/*请输入正整数*/} style={{ width: '120px' }}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key180')/*格式*/} {...formItemLayout}>
            {getFieldDecorator('type', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
              initialValue: record.ruleDetail && JSON.parse(record.ruleDetail).type.toString()
            })(
              <RadioGroup onChange={this.changeRadio}>
                <Radio key={'1001'} value={'1001'}>{messages('financial-account.key181')/*自然数*/}</Radio>
                <Radio key={'1002'} value={'1002'}>{messages('financial-account.key182')/*固定位数，不足补0*/}</Radio>
              </RadioGroup>
            )}
          </FormItem>
          {
            type === '1002' && (
              <Row>
                <Col span={8}/>
                <Col span={14}>
                  <FormItem>
                    {getFieldDecorator('length', {
                      rules: [{
                        required: true, message: messages('common.please.enter')/*请输入*/,
                      }],
                      initialValue: record.ruleDetail && JSON.parse(record.ruleDetail).length
                    })(
                      <InputNumber step={1} min={1} precision={0} placeholder={messages('financial-account.key178')/*请输入正整数*/}
                                   style={{ width: '120px' }}/>
                    )}
                  </FormItem>
                </Col>
              </Row>
            )
          }
          <FormItem label={messages('common.column.status')/*状态*/} {...formItemLayout}>
            {getFieldDecorator('isEnable', {
              initialValue: typeof record.isEnable === "boolean" ? record.isEnable : true,
              valuePropName: 'checked'
            })(
              <Switch/>
            )}
          </FormItem>
        </Form>
        <div className="footer-operate" style={{ backgroundColor: '#ffffff', left: '0px' }}>
          <Button type="primary" onClick={this.handleSave} style={{ margin: '0px 10px' }}
                  loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    tenant: state.login.tenant
  }
}

const wrappedRuleDefinedRule = Form.create()(ruleDefinedRule);
export default connect(mapStateToProps)(wrappedRuleDefinedRule);
